package LC;

/**
 * @ClassName LC148
 * @Description: TODO
 * @Author hl
 * @Date 2020/8/5
 * @Version V1.0
 **/

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
 }


public class LC148 {

    public static void main(String[] args) {
        ListNode node=new ListNode(4);
        node.next=new ListNode(2);
        node.next.next=new ListNode(1);
        node.next.next.next=new ListNode(3);
        node.next.next.next.next=new ListNode(5);
        sortList(node);
    }

    public static ListNode sortList(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode fast = head.next, slow = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode tmp = slow.next;
        slow.next = null;
        ListNode left = sortList(head);
        ListNode right = sortList(tmp);
        ListNode h = new ListNode(0);
        ListNode res = h;
        while (left != null && right != null) {
            if (left.val < right.val) {
                h.next = left;
                left = left.next;
            } else {
                h.next = right;
                right = right.next;
            }
            h = h.next;
        }
        h.next = left != null ? left : right;
        return res.next;
    }

}
